package com.crop.back.common.utils;

import io.minio.BucketExistsArgs;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MakeBucketArgs;
import io.minio.RemoveObjectArgs;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.http.Method;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

@Component
@Data
@Slf4j
public class OssUtil {
    private static final Logger logger = LoggerFactory.getLogger(OssUtil.class);
    private static final String BUCKET_NAME = "pzwdp9do-ticket";
    private static final List<String> allowedTypes = Arrays.asList(
            "image/jpeg", "image/png", "image/gif",
            "application/pdf", "application/msword",
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            "application/vnd.ms-excel",
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            "application/vnd.openxmlformats-officedocument.word",
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    );
    
    @Autowired
    private MinioClient minioClient;
    

    /**
     * 设置文件上传路径（prefix + 日期 + uuid + suffix）
     */
    public String getPath(String prefix, String suffix) {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String path = dateTimeFormatter.format(LocalDateTime.now()) + "/" + uuid;
        if (StringUtils.isNotEmpty(prefix)) {
            path = prefix + "/" + path;
        }
        return path + "-" + suffix;
    }


    /*
     * @description: 
     * @param file
     * @return: ResultBean
     * @time: 2024/12/25 18:03
     */
    public String uploadFile(MultipartFile file) {
        try {
            // 检查文件大小（限制为10MB）
            long maxFileSize = 10 * 1024 * 1024; // 10MB in bytes
            if (file.getSize() > maxFileSize) {
                return "文件大小不能超过10MB";
            }

            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType != null && contentType.length() > 50) {
                contentType = contentType.substring(0, 50);
            }

            // 允许的文件类型列表

            if (!allowedTypes.contains(contentType)) {
                return "不支持的文件类型，请上传图片、PDF或Office文档";
            }

            // 生成文件UUID
            String fileUUID = UUID.randomUUID().toString().replaceAll("-", "");
            String saveFileName = fileUUID + "_" + file.getOriginalFilename();

            // 确保bucket存在
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(BUCKET_NAME).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(BUCKET_NAME).build());
            }

            // 上传文件到MinIO
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(BUCKET_NAME)
                            .object(saveFileName)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build()
            );

            // 获取文件的URL
            String fileUrl = minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .method(Method.GET)
                            .bucket(BUCKET_NAME)
                            .object(saveFileName)
                            .expiry(7, TimeUnit.DAYS)  // URL有效期7天
                            .build()
            );
            return fileUrl;
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return "文件上传失败：" + e.getMessage();
        }
    }

    
    /**
     * 获取文件 url
     */
    public String getUrl(String key) {
        try {
            String url = minioClient.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder()
                    .bucket(BUCKET_NAME)
                    .object(key)
                    .expiry(7, TimeUnit.DAYS)
                    .build()
            );
            logger.info("Generated URL for key: {}", key);
            return url;
        } catch (Exception e) {
            logger.error("Failed to get URL for key: {}", key, e);
            throw new RuntimeException("获取文件 url 失败", e);
        }
    }

    /**
     * 删除 OOS 中的文件
     */
    public void deleteObject(String objectName) {
        try {
            minioClient.removeObject(
                RemoveObjectArgs.builder()
                    .bucket(BUCKET_NAME)
                    .object(objectName)
                    .build()
            );
            logger.info("File deleted successfully: {}", objectName);
        } catch (Exception e) {
            logger.error("Failed to delete file: {}", objectName, e);
            throw new RuntimeException("删除文件失败", e);
        }
    }
}
